{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import xml.dom.minidom\n",
    "import os\n",
    "import wget"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "sourceurl = 'https://pythonbytes.fm/episodes/rss'\n",
    "resp = requests.post(sourceurl)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "respxml = resp.content\n",
    "DOMTree = xml.dom.minidom.parseString(respxml)\n",
    "collection = DOMTree.documentElement\n",
    "items = collection.getElementsByTagName(\"item\").__reversed__()\n",
    "# 创建存放文件的文件夹\n",
    "if not os.path.exists('download'):\n",
    "    os.makedirs('download')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "files download start\n",
      "download/#1 Intro to the show and pip 9 is out!.mp3 start\n",
      "download/#1 Intro to the show and pip 9 is out!.mp3 downloaded\n",
      "download/#2 PyCon, awesome python, python developer job prospects, and more.mp3 start\n"
     ]
    }
   ],
   "source": [
    "# 逐一下载文件\n",
    "print('files download start')\n",
    "for item in items:\n",
    "    title = item.getElementsByTagName('title')[0].childNodes[0].data\n",
    "    url = item.getElementsByTagName('enclosure')[0].getAttribute(\"url\")\n",
    "    interval = item.getElementsByTagName('itunes:duration')[0].childNodes[0].data\n",
    "    filename = \"download/\"+title + '.mp3'\n",
    "    if os.path.isfile(filename):\n",
    "        print(filename,\"exist!\")\n",
    "        continue\n",
    "    print(filename,\"start\")\n",
    "    try:\n",
    "        print(url)\n",
    "        wget.download(url, out = filename)\n",
    "    except:\n",
    "        print(filename,\"download fail\")\n",
    "        continue\n",
    "    print(filename,\"downloaded\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
